package com.poem.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.poem.constant.MessageConstant;
import com.poem.dto.TypesQueryDTO;
import com.poem.entity.Types;
import com.poem.exception.BaseException;
import com.poem.mapper.PoemsMapper;
import com.poem.mapper.TypesMapper;
import com.poem.result.PageResult;
import com.poem.service.TypesService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName: TypesServiceImpl
 * @Author: YLY
 * @Description:
 * @Date: 2025/10/19
 * @Version: 1.0
 */

@Service
public class TypesServiceImpl implements TypesService {

    @Resource
    private TypesMapper typeMapper;
    @Resource
    private PoemsMapper poemsMapper;

    /**
     * 查询所有类型
     * 
     * @return
     */
    public List<Types> queryAllTypes() {
        return typeMapper.queryAllTypes();
    }

    /**
     * 添加类型
     * 
     * @param type
     */
    public void addType(Types type) {
        typeMapper.addType(type);
    }

    /**
     * 修改类型
     * 
     * @param type
     */
    public void updateType(Types type) {
        // 检查题材是否存在
        Types existingType = typeMapper.getById(type.getId());
        if (existingType == null) {
            throw new BaseException(MessageConstant.TYPE_NOT_EXISTS);
        }

        typeMapper.updateType(type);
    }

    public PageResult<Types> pageQuery(TypesQueryDTO typesQueryDTO) {

        PageHelper.startPage(typesQueryDTO.getPage(), typesQueryDTO.getPageSize());

        Page<Types> page = typeMapper.pageQuery(typesQueryDTO);

        return new PageResult(page.getTotal(), page.getResult());
    }

    public void deleteBatch(List<Long> ids) {
        for (Long id : ids) {
            // 检查题材是否存在
            Types type = typeMapper.getById(id);
            if (type == null) {
                throw new BaseException(MessageConstant.TYPE_NOT_EXISTS);
            }

            // 检查是否有诗歌关联
            Integer poemCount = poemsMapper.countByType(id);
            if (poemCount != null && poemCount > 0) {
                throw new BaseException(type.getTypeName() + MessageConstant.TYPE_HAS_POEMS);
            }
        }

        typeMapper.deleteBatch(ids);
    }
}
